package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
	"syscall"

	socketio "go-socket/go-socket-io"

	"github.com/gin-gonic/gin"
)

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method               // 请求方法
		origin := c.Request.Header.Get("Origin") // 请求头部
		var headerKeys []string                  // 声明请求头keys
		for k, _ := range c.Request.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ", ")
		if headerStr != "" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", origin)                                    // 这是允许访问所有域
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") // 服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
			//  header的类型
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			//              允许跨域设置                                                                                                      可以返回其他子段
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
			c.Header("Access-Control-Max-Age", "172800")                                                                                                                                                           // 缓存请求信息 单位为秒
			c.Header("Access-Control-Allow-Credentials", "true")                                                                                                                                                   //  跨域请求是否需要带cookie信息 默认设置为true
			c.Set("content-type", "application/json")                                                                                                                                                              // 设置返回格式是json
		}

		// 放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "Options Request!")
		}
		// 处理请求
		c.Next() //  处理请求
	}
}

func main() {

	// Set a new limit
	newRlimit := &syscall.Rlimit{
		Cur: 10000,
		Max: 10000,
	}
	err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, newRlimit)
	if err != nil {
		fmt.Println("Error setting rlimit:", err)
		return
	}
	fmt.Println("New rlimit:", newRlimit)

	router := gin.New()
	log.SetFlags(log.Lshortfile | log.LstdFlags)
	server := socketio.NewServer(nil)
	// 连接成功
	go server.OnConnect("/", func(s socketio.Conn) error {
		s.SetContext("")
		// 申请一个房间
		s.Join("bcast")
		fmt.Printf("连接成功:%s ,连接数%d\n", s.ID(), server.Count())
		return nil
	})

	// 接收”notice“事件
	server.OnEvent("/", "notice", func(s socketio.Conn, msg string) {
		s.Emit("reply", "have "+msg) // 回复内容
		log.Println("notice收到内容：:", msg)
	})

	server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string {
		s.SetContext(msg)
		fmt.Println("=====chat====>", msg)
		return "recv " + msg
	})

	server.OnEvent("/", "bye", func(s socketio.Conn, msg string) string {
		last := s.Context().(string)
		s.Emit("bye", msg)
		fmt.Println("============>", last)
		return last
	})

	//----------------------------房间操作----------------------------------
	server.OnEvent("/", "join", func(s socketio.Conn, msg string) {
		server.BroadcastToRoom("", "bcast", "event:name", msg)
	})

	router.GET("/room", func(context *gin.Context) {
		// 向房间内的所有人员发消息
		server.BroadcastToRoom("", "bcast", "event:name", "通知")
		fmt.Println("=========向房间内的所有人员发消息======>")
	})

	//----------------------------------end----------------------------------

	// 连接错误
	server.OnError("/", func(s socketio.Conn, e error) {
		log.Println("连接错误:", e)

	})
	// 关闭连接
	server.OnDisconnect("/", func(s socketio.Conn, reason string) {
		log.Printf("关闭连接：%s,连接数%d\n", reason, server.Count())
	})

	go server.Serve()
	defer server.Close()

	router.Use(gin.Recovery(), Cors())
	router.GET("/socket.io/*any", gin.WrapH(server))
	router.POST("/socket.io/*any", gin.WrapH(server))
	router.StaticFS("/public", http.Dir("../asset"))

	log.Println("Serving at localhost:8000...")
	if err := router.Run(":8000"); err != nil {
		log.Fatal("failed run app: ", err)

	}
}
